var WEB_SERVICE_NAME = "";
var WEB_SERVICE_URL = "";
var WEB_SERVICE_LOADING = "Sorry.\n\nPage is loading. Try again!";
var WS = null;
function checkWS(mute,wsObject){
    if( arguments.length == 2 && wsObject )return true;
	if( arguments.length < 2 && WS )return true;
	if( !mute )alert(WEB_SERVICE_LOADING);
	return false;
}
function initWS(name,url,onserviceavailable){
    var tagID = "ws";
    if( typeof(name) == 'object' ){
        tagID = name.tagID;
        name = name.wsName;
     }
        
//    if( typeof(userName) != 'undefined' && userName == 'help'){
//        debugger;
//    }
	if( initWS.bid )return alert("BehaviorID:"+initWS.bid);
	if( !document.body )return setTimeout(function(){return initWS(name,url,onserviceavailable)},300);
	//debugger;
	//if( typeof(document.all.ws) == 'undefined' && !isDocReadyEx() )return setTimeout(function(){return initWS(name,url,onserviceavailable)},300);
	if( url  )url = sureURL(url);
	if( !document.all[tagID] ){
		var div = document.createElement("DIV");
		div.id = tagID;
		document.body.insertBefore(div);
	}
	//ws.style.display = "none";
	var ws = document.all[tagID];
	ws.onreadystatechange = function(){debugger;}
	ws.onserviceavailable = onserviceavailable || function(){WS = this[name].callService};
	ws.onreadystatechange = function(){if(this.readyState=='complete')this.useService(url,name)};
	initWS.bid = ws.addBehavior("/include/htc/webservice_d.htc");
	for( var foo in attachToWS.handlers )
		ws.attachEvent("onserviceavailable",attachToWS.handlers[foo]);
	if( !ws.TimeTag )ws.TimeTag = top.WS_TIME_TAG;
}
function attachToWS(foo){
	if( !attachToWS.handlers )attachToWS.handlers = [];
	attachToWS.handlers.push(foo);
}
function hostAddress(){return location.protocol+"//"+location.host}
function sureURL(url){
	if( url.indexOf(":") < 0 )
		url = url.indexOf("/") == 0 ? getLocationRootPath()+url : getLocationPath()+url;
	if( !url.match(/[&?]WSDL/i) )
		url = addURLParam(url,"WSDL");
	var applID = url.match(/applid=\d*/i) ? undefined : getParam("ApplID");
	return unescape(url)+(applID?"&ApplID="+applID:"");
	// Locals
	function addURLParam(url,param){
		if( url.indexOf("?") < 0 )return url+"?"+param;
		return (url+"&"+param).replace("?&","?");
	}
}
function getLocationPath(){return location.href.match(/(.+\/).*?$/)[1]}
function getLocationRootPath(){return location.href.match(/.+\/\/[^/]*/)[0];}
function CO(methodName,wsObject){
	if( !arguments.length )methodName = getFuncName(arguments.callee.caller||CO.caller);
	if( !methodName )return alert("No MethodName provided.");
	return (wsObject||ws).createCallOptions(methodName,undefined,false)
}
function showSOAPError(result,silent){
	return isWSError(result,silent);
	if( !result.error )return false;
	return alert(result.errorDetail.string) || true;
}
function isWSError(ret,silent){
	if( !ret.error )return false;
	if( silent )return ret.errorDetail.string;
	return showSOAPAlert(ret.errorDetail.string);
}
var reXmlMessage = /<(\S+?).*>([\s\S]*?)<\/\1>/;
function showSOAPAlert(errorString){
var XML_WS_EXCEPTION = "xmlWSException";
var NS_CLIENT_EXEPTION = /.+\/ClientException$/;
	if( !errorString )return false;
	if( typeof(document.all[XML_WS_EXCEPTION]) == 'undefined' )
		document.body.insertAdjacentHTML("beforeEnd","<xml id='"+XML_WS_EXCEPTION+"'></xml>");
	var xml = document.all[XML_WS_EXCEPTION];
	var message = errorString.match(reXmlMessage) || htmlDecode(errorString).match(reXmlMessage);
 if( message ){
		xml.loadXML(message[0]);
		var rs = xml.recordset;
		try{
			if(rs.Fields("xmlNS").Value.match(NS_CLIENT_EXEPTION)) // it's a client type exception
				message = xml.recordset.Fields("ClientExceptionDataSet").value.Fields("Message").value
		}catch(e){}
	}
	var header = "<DIV title='"+(callStack()||[]).join("\n")+"'><BR>";
	return returnError(header+htmlDecode(message||errorString)+"</DIV>");
	// Locals
	function returnError(msg){
		return alertHTML(msg || errorString,null) || true;
	}
}
/// Update Field by dataSrc and dataFld or fieldName and fieldValue
function UF_AddCallBacks(fooName,foo1,foo2,foo3,fooN){
	if( typeof(fooName) != 'string' )return alert("fooName is not a name:\n"+fooName);
	eval((UF+"").replace(/ UF\(/," "+fooName+"("));
	var _uf = eval(fooName);
	_uf.callBacks = new Array();
	for( var i=1; i < arguments.length; i++ )
		_uf.callBacks.push(arguments[i]);
	return _uf;
}
function UF_AddCallBack(foo){
	if( !UF.callBacks )UF.callBacks = new Array();
	UF.callBacks.push(foo);
}
function UF(el,fieldName,fieldValue,wsMethod,rowID,arg1,arg2){
	el = el || event.srcElement || {getAttribute:function(){}};
	fieldName = defined(fieldName)?fieldName:(el.getAttribute("FieldName")||el.dataFld||el.dataField);
	if( !fieldName )return;
	fieldName = fieldName.replace(/_F$/,"");
	fieldValue = defined(fieldValue)?fieldValue:getElementValue(el,true);
	if( !fieldValue )
		if( el.getAttribute("null") != null || _isNumeric(el) )fieldValue = null;
		else if( el.getAttribute("default") != null )fieldValue = el.getAttribute("default");
	if( fieldValue && el && _isNumeric(el) )fieldValue = eval(fieldValue);
//	if( !checkWS(true,(arguments.callee.callService||WS)) )
//	    return setTimeout(function(){
//	        if( arguments.callee.caller == arguments.callee )return;
//    	    return arguments.callee(el,fieldName,fieldValue,wsMethod,rowID,arg1,arg2)
//    	  },500) && false;
	if( el && el.getAttribute("encode") !== null )fieldValue = encodeXML(fieldValue);
	if( rowID == undefined )rowID = (((getParentTR(el)||{}).all||{}).id||{}).innerText;
	if( rowID == undefined )rowID = _ID(el);
	wsMethod = wsMethod || _wsMethod(el);
	var ret = (arguments.callee.callService||WS)(CO(wsMethod,arguments.callee.wsTag),fieldName,typeof(fieldValue)=="string"?encodeXML(fieldValue):fieldValue ,rowID,arg1,arg2);
	(event||{}).returnValue = false;
	if( showSOAPError(ret) ){
		if( el.tagName == "SELECT" )
			try{
				el.value = rsField(el,el.dataFld).value;
			}catch(e){
				setTimeout(function(){document.body.focus()},100);
			}
		if( !arguments.callee.passTrough ) return false;
	}
	if( el.tagName == "SELECT" )setTimeout(function(){document.body.focus()},100);
	(event||{}).returnValue = ret;
	(event||{}).arguments = arguments;
	var callBacks = arguments.callee.callBacks;
	for( var i=0; callBacks && i < callBacks.length; i++ )
		callBacks[i](ret,el,fieldName,fieldValue,wsMethod);
	if( _isNumeric(el) && el.value != fieldValue )el.value = fieldValue || "";
	return ret;
	// Local
	function _ID(el){
		try{var rs = rsFromElement(el);
				var ID_Name = el.getAttribute("IDName") || "ID";
				return rs.Fields(0).Name != "$Text" ? rs(ID_Name).Value : 0;
		}catch(e){return}
	}
	// Local
	function _isNumeric(el){return el.getAttribute("numeric") != null;}
	function _encode(el){return el && el.getAttribute("encode") !== null;}
	function _wsMethod(el){
		var attr = "wsMethod";
		var wm = el.getAttribute(attr);
		if( !wm )wm = getDataSrcContainer(el).getAttribute(attr);
		if( !wm ){
			var p = getParentByAttrEx(el,attr);
			if( p ) wm = p.getAttribute(attr);
		}
		if( !wm )wm = getDataSrc(el);
		return wm;
	}
}
function initInputs(tagName,attachedEvents,doc,ufFoo){
	if( attachedEvents && !attachedEvents.length )attachedEvents = new Array(attachedEvents);
	ufFoo = ufFoo || UF;
	if( attachedEvents && attachedEvents.length == undefined )attachedEvents = [attachedEvents];
	if( !tagName ){
		var aTags = new Array("INPUT","TEXTAREA","SELECT");
		for( var i=0; i < aTags.length; i++ )
			initInputs(aTags[i],attachedEvents,doc,ufFoo);
		return;
	}
	var inps = (doc||document).all.tags(tagName);
	for( var i=0; i < inps.length; i++ ){
		if( inps[i].type == "button" )continue;
		var onEvent = inps[i].type=='checkbox'?"onclick":"onchange";
		if( !inps[i][onEvent] ){
			if( !inps[i][onEvent] )inps[i][onEvent] = function(){return ufFoo()};
			for( var j=0; j < (attachedEvents||[]).length; j++ )
				inps[i].attachEvent(attachedEvents[j].eventName,attachedEvents[j].eventHandler);
		}
		if( !inps[i].onfocus )inps[i].onfocus = function(){try{this.select()}catch(e){}};
	}
}
function isDocReadyEx(){
	try{return document.readyState == "complete";}catch(e){ }
	return frameElement.document.readyState == "complete";
}
function htmlDecode(text){
 var HTML_WS_EXCEPTION = "htmlWSException";
	if( typeof(document.all[HTML_WS_EXCEPTION]) == 'undefined' )
  document.body.insertAdjacentHTML("beforeEnd","<pre style='white-space:pre;display:none' id='"+HTML_WS_EXCEPTION+"'></pre>")
 var preHtml = document.all[HTML_WS_EXCEPTION];
 preHtml.innerHTML = "<pre>"+text+"</pre>";
	return preHtml.innerText;
}
function htmlEncode(text){
	var a = new Array(['&',"&amp;"],['"',"&quot;"],['<',"&lt;"],['>',"&gt;"]);  
	for( var i = 0; i < a.length; i++ )
		text = text.replace(a[i][0],a[i][1]);
	return text;
}
function encodeXML(text){
	var xml = new ActiveXObject("Msxml2.DOMDocument");
	var root = xml.createElement("TAG");
	root.text = text||"";
	text = root.xml.replace(/<.+?>/g,"");
	root = null;
	xml = null;
	return text;
}
 